﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace SweetSQL.Data
{
    internal static class PropertyCache
    {
        private static Dictionary<Type, Dictionary<string, PropertyInfo>> _properties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

        private static Dictionary<string, PropertyInfo> Reflect(Type type)
        {
            PropertyInfo[] propertiesArray = type.GetProperties();
            Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
            int length = propertiesArray.Length;
            PropertyInfo property = null;
            for (int i = 0; i < length; i++)
            {
                property = propertiesArray[i];
                properties[property.Name] = property;
            }
            return properties;
        }

        public static Dictionary<string, PropertyInfo> GetProperties(Type type)
        {
            lock (_properties)
            {
                Dictionary<string, PropertyInfo> properties = null;
                if (!_properties.TryGetValue(type, out properties))
                {
                    _properties[type] =
                        properties = Reflect(type);
                }
                return properties;
            }
        }
    }

    internal static class PropertyCache<T>
        where T : class
    {
        private static Dictionary<string, PropertyInfo> _properties = new Dictionary<string, PropertyInfo>();

        static PropertyCache()
        {
            _properties = PropertyCache.GetProperties(typeof(T));
        }

        public static Dictionary<string, PropertyInfo> Properties
        {
            get { return _properties; }
        }
    }
}
